package com.yongqi.duocai.utils;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.io.InputStream;
import java.security.*;


/**
 * 1.描述（@desc）：
 * 2.作者（@author）：夏亮辉
 * 3.日期（@date）：2021年07月02  10:15
 * 4.版本（@version）：1.0.0
 * 5.版权：
 */

public class WXPayUtils {

    private  static String MCH_ID = "1578360971";

    /**
     * 微信退款
     * @param url 申请地址
     * @param data 退款xml
     * @return
     */
    public  static  String doWechatRefund(String url, String data) throws IOException, KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        InputStream inputStream = classLoader.getResourceAsStream("apiclient_cert.p12");
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        try {
            // 装载证书
            keyStore.load(inputStream,MCH_ID.toCharArray());
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            inputStream.close();
        }
        SSLContext sslcontext = SSLContexts.custom()
                                .loadKeyMaterial(keyStore, MCH_ID.toCharArray())
                                .build();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslcontext, new String[] { "TLSv1" }, null,
                SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();

        try {
            HttpPost httpost = new HttpPost(url);  //设置响应头信息
            httpost.addHeader("Connection", "keep-alive");
            httpost.addHeader("Accept", "*/*");
            httpost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            httpost.addHeader("Host", "api.mch.weixin.qq.com");
            httpost.addHeader("X-Requested-With", "XMLHttpRequest");
            httpost.addHeader("Cache-Control", "max-age=0");
            httpost.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
            httpost.setEntity(new StringEntity(data, "UTF-8"));
            CloseableHttpResponse response = httpclient.execute(httpost);
            try {
                HttpEntity entity = response.getEntity();
                String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
                EntityUtils.consume(entity);
                return jsonStr;
            } finally {
                response.close();
            }
        }finally {
            httpclient.close();
        }

    }
}
